﻿using System;
using System.Data;
using System.Data.Common;
using System.Data.SQLite;

namespace glTech.CommonLib.Data
{

    public class SqliteDatabase : Database, IDatabase
    {
        public SqliteDatabase(string connectionString) : base(connectionString)
        {

        }


        public override TResult Execute<TResult>(string commandText, CommandType commandType, DbParameter[] dbParameters,
           bool useTransaction, Func<DbCommand, TResult> executor)
        {
                TResult result = default(TResult);
                DbConnection connection = new SQLiteConnection(_connection.ConnectionString);

                using (connection)
                {
                    connection.Open();
                    DbCommand command = connection.CreateCommand();
                    DbTransaction transaction = useTransaction ? connection.BeginTransaction() : null;
                    command.Connection = connection;
                    command.CommandType = commandType;
                    command.CommandText = commandText;
                    command.Transaction = transaction;
                    if (dbParameters != null && dbParameters.Length > 0)
                    {
                        command.Parameters.AddRange(dbParameters);
                    }
                    result = executor(command);

                    // Commit transaction if enabled.
                    if (useTransaction) transaction.Commit();
                }
                return result; 
        }
    }
}
